package reflect.field;

import java.lang.reflect.Field;

public class Fields {
    public static void main(String[] args) throws Exception {
        // 1、获取CLass对象
        Class stuClass = Class.forName("reflect.field.Student");
        // 2、获取字段
        System.out.println("----------获取所有公有的字段-----------");
        Field[] fieldArray = stuClass.getFields();
        for (Field f : fieldArray) {
            System.out.println(f);
        }

        System.out.println("----------获取所有的字段-----------");
        fieldArray = stuClass.getDeclaredFields();
        for (Field f : fieldArray) {
            System.out.println(f);
        }

        System.out.println("---------获取公有字段并调用----------");
        Field f = stuClass.getField("name");
        System.out.println(f);
        Object obj = stuClass.getConstructor().newInstance();   // 获取一个对象
        f.set(obj, "刘德华");
        Student stu = (Student)obj;
        System.out.println("验证姓名：" + stu.name);

        System.out.println("---------获取私有字段并调用----------");
        f = stuClass.getDeclaredField("phoneNum");
        System.out.println(f);
        f.setAccessible(true);  // 暴力反射，解除私有限定
        f.set(obj, "1888888999");
        System.out.println("验证电话：" + stu);
    }
}
